package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 体检预约
     * @param map
     * @return
     */
        @RequestMapping("/submit")
        public Result submit(@RequestBody Map map){

                //从Redis中获取验证码
                //将用户名和电话号码进行比对，如果一致，则预约成功，否则预约失败
                String code = (String) redisTemplate.opsForValue().get("code");
                String telephone = (String) map.get("telephone");
                String orderDate = (String) map.get("orderDate");
            if(code != null && code.equals(map.get("validateCode"))){
                    //验证码一致
                        map.put("orderType", Order.ORDERTYPE_WEIXIN);
                    Result result = null;
                    try {
                        //预约成功
                         result = orderService.submit(map);
                    } catch (Exception e) {
                        //预约失败
                        return new Result(false, MessageConstant.ORDER_FAIL,result);
                    }
                    if (result.isFlag()){
                        //发送短信
                        try {
                            SMSUtils.sendMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return result;
                }else {
                    return new Result(false, MessageConstant.VALIDATECODE_ERROR);
                }

        }

    /**
     * 根据id查询预约信息
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        log.info("根据id查询预约信息：{}",id);
        try {
            //调用service
           Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
        }
    }
}
